<template>
	<section >
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getDepartments">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" :height="350" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="姓名" width="120" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="标识" width="120" sortable>
			</el-table-column>
			<el-table-column prop="dirPath" label="上级路径" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100"  sortable>
				<template scope="scope">
					<span v-if="scope.row.state == 0" style="color: #11b95c">启用</span>
					<span v-else-if="scope.row.state == -1" style="color: red">禁用</span>
					<span v-else="scope.row.state" style="color: #8c939d">未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="100" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="父部门" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页条+ 批量删除-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"  @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="page"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面
			:rules 申明数据校验规则
		-->
		<el-dialog title="新增/编辑" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
			<el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="departmentForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="标识" prop="sn">
					<el-input v-model="departmentForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="departmentForm.state">
						<el-radio class="radio" :label="0">启用</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理员" prop="manager">
					<!--
						：key：选择项的key
						:value：选择项对应的value 也就是需要传给后端的值
						value-key="id"：如果value需要传递对象，那么该值必填
						:label:选项框中显示的内容
					-->
					<el-select v-model="departmentForm.manager" placeholder="请选择" value-key="id">
						<el-option
								v-for="item in employees"
								:key="item.id"
								:label="item.username"
								:value="item">
							<span style="float: left">{{ item.username }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="父级部门" prop="parent">
					<!--<el-input v-model="departmentForm.parent" auto-complete="off"></el-input>-->
					<el-cascader
							v-model="departmentForm.parent"
							:options="deptTree"
							:props="{
							   checkStrictly: true,
							   value:'id',
							   label:'name'
							    }"
							clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="departmentSubmit" :loading="departmentLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
                    keyword: ''
				},
				departments: [],
                employees:[],
                deptTree:[],
				total: 0,
				page: 1,
                pageSize:10,
				listLoading: false,
				sels: [],//列表选中列

				departmentFormVisible: false,//弹出框界面是否显示
				departmentLoading: false,//忙等框
				departmentFormRules: {//绑定表单校验规则
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
                    sn: [
                        { required: true, message: '请输入标识', trigger: 'blur' }
                    ]

				},

				//编辑界面数据
				departmentForm: {
					id: null,
					name: '',
                    sn: '',
                    state: -1,
                    manager:null,
                    parent:null
				}

			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.state == 0 ? '启用' : row.state == -1 ? '禁用' : '未知';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
				let para = {
					currentPage: this.page,
                    keyword: this.filters.keyword
				};
				this.listLoading = true;
				//NProgress.start();

				//http://localhost:8080/dept
				this.$http.post("/dept",para)
					.then(result=>{
                        this.listLoading = false;
                        result = result.data;//直接抽取了一层
                        this.total = result.total;
                        this.departments = result.rows;
					})
					.catch(result=>{
						alert("系统错误！！！");
                        this.listLoading = false;
                    })

			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '温馨提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let url = "/dept/"+row.id;
					this.$http.delete(url,{})
						.then(result=>{
                            this.listLoading = false;
                            result = result.data;//直接抽取了一层
                            if(result.success){//true
								this.page = 1;//定位第一页
                                this.$message({
                                    message: result.message,
                                    type: 'success'
                                });
                            }else{//false
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                            this.getDepartments();//刷新页面
						})
						.catch();
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.departmentFormVisible = true;//弹出编辑框
				//Object.assign  克隆数据
				this.departmentForm = Object.assign({}, row);//数据回显
                //this.$refs['departmentForm'].resetFields();//重置表单校验
                //this.departmentForm.parent  = [ 1, 27 ];  模拟数据

				let dirParth = this.departmentForm.dirPath;//  /1/27
				let temp = [];
				if(dirParth){//数据库中有脏数据
                    let arry = dirParth.trim().split("/");//['','1','27','56']
					for(let i=1; i<arry.length-1; i++){
                        temp[i-1] = parseInt(arry[i]);
					}
                    this.departmentForm.parent = temp;
				}
                this.getDeptTree();
			},
			//显示新增界面
			handleAdd: function () {
				this.departmentFormVisible = true;
				this.departmentForm = {//清空页面数据
                    id: null,
                    name: '',
                    sn: '',
                    state: -1,
                    manager:null,
                    parent:null
				};
                //this.$refs['departmentForm'].resetFields();//重置表单校验
				this.getDeptTree();
			},
			//新增或编辑
			departmentSubmit: function () {
				this.$refs.departmentForm.validate((valid) => {//通过ref别命名找到所有的rules中表单校验并执行它
                        if (valid) {
						this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
							this.departmentLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.departmentForm);
							if(para.parent){//如果是顶级部门
                                console.log(para.parent);//[1,37,58] {id:37}
                                let parent = {"id":para.parent[para.parent.length-1]}
                                para.parent = parent;
                                /*let strPath = "/";//  /1/37/58/
                                for(let i=0;i<para.parent.length;i++){
                                    strPath += para.parent[i] +"/";
								}
                                para.dirPath = strPath;*/
							}

							// 数据格式处理
							this.$http.put("/dept",para)
                                .then(result=>{
                                    this.departmentLoading = false;//关闭忙等框
                                    result = result.data;//直接抽取了一层
                                    if(result.success){//true
                                        this.$message({
                                            message: result.message,
                                            type: 'success'
                                        });
                                    }else{//false
                                        this.$message({
                                            message: result.message,
                                            type: 'error'
                                        });
                                    }
                                    this.page = 1;//定位第一页
                                    this.getDepartments();//刷新页面
                                    this.$refs['departmentForm'].resetFields();//重置页面表单验证
                                    this.departmentFormVisible = false;
                                })
                                .catch(result=>{
                                    alert("系统错误！");
									this.departmentLoading = false;
								});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);//[1,2]
				console.log(ids);
				this.$confirm('确认删除选中记录吗？', '温馨提示', {
                    type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.patch("/dept",ids)
						.then(result=>{
						    result = result.data;
						    if(result.success){
                                this.$message({
                                    message: result.message,
                                    type: 'success'
                                });
							}else{
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
							}
                            this.listLoading = false;//关闭忙等框
                            this.page = 1;
                            this.getDepartments();
						})
						.catch(result=>{
                            this.$message({
                                message: '系统异常',
                                type: 'error'
                            });
                        })
				}).catch(() => {

				});
			},
			/*查询所有的员工信息*/
            getEmployees(){
			    this.$http.get("/employee")
					.then(result=>{
					    if(result){
					        this.employees = result.data;
						}
					})
			},
            getDeptTree(){
                this.$http.get("/dept/deptTree")
                    .then(result=>{
                        if(result){
                            this.deptTree = result.data;
                        }
                    })
			}
		},
		mounted() {
			this.getDepartments();
			this.getEmployees();//页面加载完成，请求所有的员工数据，以备不时之需
		}
	}

</script>

<style scoped>

</style>